package com.apartment.common.utils.date;

import cn.hutool.core.date.DateUtil;
import com.apartment.common.core.domain.entity.SysUser;
import org.springframework.format.annotation.DateTimeFormat;
import sun.java2d.pipe.SpanIterator;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 根据一段时间区间，按月份拆分成多个时间段
 *
 * @author wjl
 */
public class SplitDateUtil {


    public static void main(String[] args) {
//        List<MyDetail> list = SplitDateUtil.getKeyValueForDate("2020-07-15", "2021-09-09", 3, 3000D,0);

//    List<MyDetail> list = SplitDateUtil.pushFixedDay("2020-07-15", "2021-09-09", 2, 3000D, 13);
        List<MyDetail> list = SplitDateUtil.getSplitDate("2020-08-17", "2020-09-15", 1, 3000D, 0,0.1);
        list.forEach(System.out::println);
        System.out.println(isFullMonth("2020-01-31", "2020-03-02"));
    }

    /**
     * @param startDate: 开始日期
     * @param endDate:   开始日期
     * @param cycle: 账单周期
     * @param payment: 账单金额
     * @param pushDay: 前推传正数，后推负数
     * @Description: 根据一段时间区间，按月份拆分成多个时间段
     * @return: java.util.List<com.apartment.common.utils.date.MyDetail>
     **/
    private static List<MyDetail> getKeyValueForDate(String startDate, String endDate, int cycle, Double payment,Integer pushDay,Double interest ) {
        double rentPay=payment;
        List<MyDetail> list = null;
        try {
            list = new ArrayList<MyDetail>();
            // 定义起始日期
            Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse(startDate);
            // 定义结束日期
            Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse(endDate);
            //获取开始时间本月几号
            Integer begin = d1.getDate();
            //开始时间月份
            Integer month = DateUtil.month(d1) + 1;
            //开始时间年份
            Integer year = DateUtil.year(d1);
            // 获取Calendar
            Calendar calendar = Calendar.getInstance();
            // 设置时间
            calendar.setTime(d1);
            // 设置日期为最大日期
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date d4 = new SimpleDateFormat("yyyy-MM-dd").parse(year + "-1-" + 29);
            Date d5 = new SimpleDateFormat("yyyy-MM-dd").parse(year + "-1-" + 30);
            Date d6 = new SimpleDateFormat("yyyy-MM-dd").parse(year + "-1-" + 31);
            // DateUtil.isSameDay()
            if (DateUtil.isSameDay(d1, d4) || DateUtil.isSameDay(d1, d5) || DateUtil.isSameDay(d1, d6)) {
                if (cycle == 1) {
                    calendar.set(Calendar.YEAR, year - 1);
                    calendar.set(Calendar.MONTH, 2);
                    //获取下个周期月的最大日期
                    int actualMaximumDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH + 1);
                    calendar.set(Calendar.DAY_OF_MONTH, actualMaximumDay);
                } else {
                    calendar.add(Calendar.MONTH, cycle);
                    calendar.set(Calendar.DAY_OF_MONTH, begin - 1);
                }
            } else {
                //如果开始日期是一号获取当月最后一天
                if (begin == 1) {
                    calendar.add(Calendar.MONTH, cycle - 1);
                    calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                }
                //如果begin不等于1获取当月最后begin-1天
                if (begin != 1) {
                    calendar.add(Calendar.MONTH, cycle);
                    calendar.set(Calendar.DAY_OF_MONTH, begin - 1);
                }
            }


            Date d3 = new SimpleDateFormat("yyyy-MM-dd").parse(sdf.format(calendar.getTime()));

            Date temp1 = d1;
            Date temp2 = d3;

            //结束日期小于开始日期
            if (d2.before(d1)) {
                System.out.println("请输入正确的结束日期！");
                return null;
            }
            //初始化时间
            Date indexDate = temp1;
            //结束日期大于开始日期
            while (temp2.before(d2)) {
                MyDetail myDetail = new MyDetail();
                myDetail.setStartDate(sdf.format(temp1));
                myDetail.setEndDate(sdf.format(temp2));
                if(dayComparePrecise(sdf.format(indexDate),sdf.format(temp1))>=1){
                    int hasYear = dayComparePrecise(startDate, sdf.format(temp1));
                    indexDate=temp1;
                    payment = Math.pow(1 + interest,hasYear)*rentPay;
                }
                myDetail.setRent(new BigDecimal(payment * cycle).setScale(2, BigDecimal.ROUND_HALF_UP));
                Date push = push(temp1, pushDay==null?0:pushDay);
                myDetail.setPaymentDay(sdf.format(push));
                list.add(myDetail);
                if (DateUtil.isSameDay(d1, d4) || DateUtil.isSameDay(d1, d5) || DateUtil.isSameDay(d1, d6) && cycle == 1) {
                    if (cycle == 1) {
                        calendar.add(Calendar.MONTH, 1);
                        calendar.set(Calendar.DATE, 1);
                        temp1 = calendar.getTime();
                        if (cycle > 1) {
                            calendar.add(Calendar.MONTH, cycle - 1);
                        }
                        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                        temp2 = calendar.getTime();
                    } else {
                        if (begin != 31) {
                            calendar.set(Calendar.DAY_OF_MONTH, begin);
                        }
                        if (begin == 31) {
                            calendar.add(Calendar.DAY_OF_MONTH, 1);
                        }
                        //循环开始时间
                        temp1 = new SimpleDateFormat("yyyy-MM-dd").parse(sdf.format(calendar.getTime()));
                        //获取下一个月份的begin-1天
                        calendar.setTime(temp1);
                        if (begin != 1 && begin != 31) {
                            calendar.add(Calendar.MONTH, cycle);
                            calendar.set(Calendar.DATE, begin - 1);
                        }
                        if (begin == 31) {
                            calendar.add(Calendar.MONTH, cycle - 1);
                            calendar.add(Calendar.DAY_OF_MONTH, 1);
                        }
                        if (begin == 31) {
                            if (calendar.getActualMaximum(Calendar.DAY_OF_MONTH) == 31) {
                                calendar.set(Calendar.DAY_OF_MONTH, 30);
                            } else {
                                calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                            }
                        }
                    }
                } else {
                    //月份加一
                    //判断
                    //月份是从第几天开始
                    if (begin != 31) {
                        calendar.set(Calendar.DAY_OF_MONTH, begin);
                    }
                    if (begin == 31) {
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    //循环开始时间
                    temp1 = new SimpleDateFormat("yyyy-MM-dd").parse(sdf.format(calendar.getTime()));
                    //获取下一个月份的begin-1天
                    calendar.setTime(temp1);
                    if (begin != 1 && begin != 31) {
                        calendar.add(Calendar.MONTH, cycle);
                        calendar.set(Calendar.DATE, begin - 1);
                    }
                    if (begin == 31) {
                        calendar.add(Calendar.MONTH, cycle - 1);
                        calendar.add(Calendar.DAY_OF_MONTH, 1);
                    }
                    if (begin == 1) {
                        calendar.add(Calendar.MONTH, 1);
                        calendar.set(Calendar.DATE, begin);
                        temp1 = calendar.getTime();
                        if (cycle > 1) {
                            calendar.add(Calendar.MONTH, cycle - 1);
                        }
                        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                        temp2 = calendar.getTime();
                    }

                    if (begin == 31) {
                        if (calendar.getActualMaximum(Calendar.DAY_OF_MONTH) == 31) {
                            calendar.set(Calendar.DAY_OF_MONTH, 30);
                        } else {
                            calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
                        }
                    }
                }
                //循环结束时间
                temp2 = new SimpleDateFormat("yyyy-MM-dd").parse(sdf.format(calendar.getTime()));
            }
            //最后一个月
            //计算每天应付租金
            double dayPay = new BigDecimal(payment / 30).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            //计算相差的天数
            int days = (int) ((d2.getTime() - temp1.getTime()) / (24 * 3600 * 1000));
            MyDetail myDetail = new MyDetail();
            myDetail.setStartDate(sdf.format(temp1));
            myDetail.setEndDate(sdf.format(d2));
            if(dayComparePrecise(sdf.format(indexDate),sdf.format(temp1))>=1){
                int hasYear = dayComparePrecise(startDate, sdf.format(temp1));
                payment = Math.pow(1 + interest,hasYear)*rentPay;
            }
            if (isFullMonth(sdf.format(temp1),sdf.format(d2))){
                myDetail.setRent(new BigDecimal(payment).setScale(2, BigDecimal.ROUND_HALF_UP));
            }else{
                myDetail.setRent(new BigDecimal(payment / 30).multiply(new BigDecimal(days + 1)).setScale(2, BigDecimal.ROUND_HALF_UP));
            }
            Date push = push(temp1, pushDay==null?0:pushDay);
            myDetail.setPaymentDay(sdf.format(push));
            list.add(myDetail);
        } catch (Exception e) {
            return null;
        }
        MyDetail myDetail = list.get(0);
        myDetail.setPaymentDay(myDetail.getStartDate());
        return list;
    }

    public static Date push(Date oldPaymentDate, Integer pushDay) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(oldPaymentDate);
        calendar.add(Calendar.DAY_OF_MONTH, -pushDay);
        Date newPaymentDay = calendar.getTime();
        return newPaymentDay;
    }
    /**
     * @param startDate: 开始日期
     * @param endDate:   开始日期
     * @param cycle: 账单周期
     * @param payment: 每月租金
     * @param pushDay: 前推传正数，后推负数
     * @Description: 根据一段时间区间，按月份拆分成多个时间段
     * @return: java.util.List<com.apartment.common.utils.date.MyDetail>
     **/
    public static  List<MyDetail> getSplitDate(String startDate, String endDate, int cycle, Double payment,Integer pushDay,Double interest){
        List<MyDetail> details = null;

        switch (cycle){
            case 1: details = getKeyValueForDate(startDate, endDate, cycle, payment, pushDay,interest);
                break;
            default:details = getKeyValueForDate(startDate, endDate, cycle, payment, pushDay,interest);
                MyDetail myDetail = details.get(details.size() - 1);
                final BigDecimal[] bigDecimal = {new BigDecimal("0")};
                //计算利息
                int hasYear = dayComparePrecise(startDate, myDetail.getStartDate());
                payment = Math.pow(1 + interest,hasYear)*payment;
                List<MyDetail> keyValueForDate = getKeyValueForDate(myDetail.getStartDate(), myDetail.getEndDate(), 1, payment, 0,0.0);
                keyValueForDate.forEach(x->{
                    bigDecimal[0] = bigDecimal[0].add(x.getRent());
                });
                myDetail.setRent(bigDecimal[0]);break;
        }
        return details;

    }
    /**
     * 应付日期返回上个月的固定日期
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param cycle 周期
     * @param payment 租金
     * @param fixedDay 上个月日期
     * @return
     */
    public static List<MyDetail> pushFixedDay(String startDate, String endDate, int cycle, Double payment,Integer fixedDay,Double interest){
        if (startDate==null||endDate==null||cycle<=0||payment==null||interest==null||fixedDay==null){
            return null;
        }
        List<MyDetail> list = getSplitDate(startDate, endDate, cycle, payment, 0,interest);
        String paymentDay = list.get(0).getPaymentDay();
        list.forEach(x->{
            String payDay=x.getPaymentDay();
            Date parseDay = null;
            try {
                parseDay = new SimpleDateFormat("yyyy-MM-dd").parse(payDay);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(parseDay);
            calendar.set(Calendar.MONTH,parseDay.getMonth()-1);
            int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            calendar.set(Calendar.DAY_OF_MONTH,fixedDay<=maxDay?fixedDay:maxDay);
            Date time = calendar.getTime();
            String pushDay = new SimpleDateFormat("yyyy-MM-dd").format(time);
            x.setPaymentDay(pushDay);
        });
        list.get(0).setPaymentDay(paymentDay);
        return list;
    }

    /**
     * 计算俩个如期相差年数
     * @param fromDate
     * @param toDate
     * @return
     */
    private static int dayComparePrecise(String fromDate, String toDate){

        Period period = Period.between(LocalDate.parse(fromDate), LocalDate.parse(toDate));
        StringBuffer sb = new StringBuffer();
        sb.append(period.getYears());
        return Integer.parseInt(String.valueOf(sb));
    }

    /**
     * 判断两个日期是否为一个整月
     */
    private static Boolean isFullMonth(String fromDate, String toDate) {
        Calendar calendar = Calendar.getInstance();
        Period period = null;
        try {
            Date parse = new SimpleDateFormat("yyyy-MM-dd").parse(toDate);
            calendar.setTime(parse);
            calendar.add(Calendar.DAY_OF_MONTH,1);
            Date time = calendar.getTime();
            String endDate = new SimpleDateFormat("yyyy-MM-dd").format(time);
            period = Period.between(LocalDate.parse(fromDate), LocalDate.parse(endDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int days = period.getDays();
        int months = period.getMonths();
            if (days==0&&months==1){
                return true;
            }else {
                return false;
            }
    }
}


